<template>
  <div class="app-page">
    <el-form ref="dataForm" class="form" :rules="rules" :model="temp" label-position="right" label-width="130px" style="margin: 0 50px;">
      <el-form-item label="企业名称:" prop="corpName">
        <el-input v-model.trim="temp.corpName" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="法人:" prop="corpPerson">
        <el-input v-model.trim="temp.corpPerson" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="所属区域:" prop="area" class="block">
        <el-cascader ref="cascader" v-model="temp.address" style="width: 100%;" :props="addressProps" clearable />
      </el-form-item>
      <el-form-item label="详细地址:" prop="corpAddress" class="block">
        <el-input v-model.trim="temp.corpAddress" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="客户电话:" prop="corpPhone" class="block">
        <el-input v-model.trim="temp.corpPhone" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="安全须知链接地址:" prop="securityUrl" class="block">
        <el-input v-model.trim="temp.securityUrl" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="二维码:" prop="wxUrl">
        <el-upload
          ref="upload"
          class="avatar-uploader"
          action="//upload.qiniup.com/"
          accept=".bmp, .gif, .jpg, .jpeg, .png, image/bmp, image/gif, image/jpg, image/jpeg, image/png"
          :data="qiniuData"
          :show-file-list="false"
          :on-success="(res, file)=>handleAvatarSuccess(res, file, 'wxUrl')"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="temp.wxUrl" :src="temp.wxUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item label="Logo:" prop="logoUrl">
        <el-upload
          ref="upload"
          class="avatar-uploader"
          action="//upload.qiniup.com/"
          accept=".bmp, .gif, .jpg, .jpeg, .png, image/bmp, image/gif, image/jpg, image/jpeg, image/png"
          :data="qiniuData"
          :show-file-list="false"
          :on-success="(res, file)=>handleAvatarSuccess(res, file, 'logoUrl')"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="temp.logoUrl" :src="temp.logoUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item label="芯片匹配:" class="block">
        <el-select v-model="temp.xrule" style="width: 200px;" placeholder="请选择" clearable>
          <el-option
            v-for="item in xruleMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
        <span style="margin-left: 20px;">
          最少 <el-input-number v-model="temp.xmin" style="width: 80px;" :precision="0" :controls="false" /> 位
        </span>
        <span style="margin-left: 20px;">
          最多 <el-input-number v-model="temp.xmax" style="width: 80px;" :precision="0" :controls="false" /> 位
        </span>
      </el-form-item>
      <el-form-item label="钢瓶匹配:" class="block">
        <el-select v-model="temp.grule" style="width: 200px;" placeholder="请选择" clearable>
          <el-option
            v-for="item in xruleMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
        <span style="margin-left: 20px;">
          最少 <el-input-number v-model="temp.gmin" style="width: 80px;" :precision="0" :controls="false" /> 位
        </span>
        <span style="margin-left: 20px;">
          最多 <el-input-number v-model="temp.gmax" style="width: 80px;" :precision="0" :controls="false" /> 位
        </span>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="$loadingPlugin.submit" @click="save">保存配置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import { queryMap, queryQiniuyunUploadToken, selectAreaCode, saveCorpInfo, queryCordInfo, queryCorpImages } from '@/api'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { mapGetters } from 'vuex'
  import { imgBaseUrl } from '@/utils/config'

  export default {
    name: 'CorpTab',
    data() {
      return {
        imgBaseUrl,
        corpInfo: {},
        qiniuData: { // 这里是直接绑定data的值
          key: '', // 图片名字处理
          token: '', // 七牛云token
          data: {},
          bucket: ' '
        },
        xruleMap: [],
        temp: {
          corpName: '',
          corpPerson: '',
          address: [],
          corpAddress: '',
          corpPhone: '',
          securityUrl: '',
          wxUrl: '',
          logoUrl: '',
          xrule: '',
          grule: '',
          xmin: undefined,
          xmax: undefined,
          gmin: undefined,
          gmax: undefined
        },
        rules: {
          csmPhone: [{ required: true, message: '请输入', trigger: 'change' }],
          csmName: [{ required: true, message: '请输入用户编码', trigger: 'change' }],
          orderCode: [{ required: true, message: '请输入押金单号', trigger: 'change' }],
          address: [{ required: true, message: '请选择投保地址', trigger: 'change' }],
          price: [{ required: true, message: '请输入投保金额', trigger: 'change' }]
        },
        addressProps: {
          checkStrictly: true,
          lazy: true,
          lazyLoad(node, resolve) {
            const { level, value } = node
            mergeAsyncFunc(selectAreaCode, { areaCode: value || 0 })
              .then((res) => {
                const nodes = res.data.map(item => ({
                  value: item.areaCode,
                  label: item.areaName,
                  leaf: level >= 2
                }))
                resolve(nodes)
              })
              .catch(() => {
                node.loading = false
                node.loaded = false
              })
          }
        }
      }
    },
    computed: {
      ...mapGetters([
        'userInfo', 'corpSettingData'
      ])
    },
    async created() {
      await Promise.all([this.queryOptionsMap(), this.getQiniuyunUploadToken()])
    },
    mounted() {
      this.getCorpImages()
    },
    methods: {
      async init() {
        const res = await queryCordInfo()
        this.corpInfo = res.data
      },
      async getCorpImages() {
        const res = await queryCorpImages()
        if (res.data.wxUrl) this.temp.wxUrl = res.data.wxUrl
        if (res.data.logoUrl) this.temp.logoUrl = res.data.logoUrl
      },
      // 查询枚举
      async queryOptionsMap() {
        const res = await mergeAsyncFunc(queryMap, { enumName: 'RegExpType' })
        this.xruleMap = res.data // 芯片匹配
      },
      // 获取七牛云上传token
      async getQiniuyunUploadToken() {
        const res = await queryQiniuyunUploadToken()
        this.qiniuData.token = res.data
      },
      handleAvatarSuccess(res, file, name) {
        this.temp[name] = URL.createObjectURL(file.raw)
      },
      beforeAvatarUpload(file) {
        const key = `${this.userInfo.corpCode}_${new Date().getTime()}_${file.name}`
        this.qiniuData.key = key
        return this.qiniuData
      },
      save() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const params = {
            corpName: this.temp.corpName,
            corpPerson: this.temp.corpPerson,
            corpAddress: this.temp.corpAddress,
            corpPhone: this.temp.corpPhone,
            wxUrl: this.temp.wxUrl,
            logoUrl: this.temp.logoUrl
          }
          if (this.temp.wxUrl.includes(imgBaseUrl)) params.wxUrl.replace(imgBaseUrl, '')
          if (this.temp.logoUrl.includes(imgBaseUrl)) params.logoUrl.replace(imgBaseUrl, '')
          const address = this.$refs.cascader.getCheckedNodes()[0]
          if (address) {
            const pathNodes = address.pathNodes
            params.province = pathNodes[0].label
            params.provinceCode = pathNodes[0].value
            params.city = pathNodes[1].label
            params.cityCode = pathNodes[1].value
            params.county = pathNodes[2].label
            params.countryCode = pathNodes[2].value
          } else {
            params.province = ''
            params.provinceCode = ''
            params.city = ''
            params.cityCode = ''
            params.county = ''
            params.countryCode = ''
          }
          if (this.temp.securityUrl !== '') {
            try {
              new URL(this.temp.securityUrl)
            } catch (e) {
              this.$message.warning('安全须知链接不合法')
              return
            }
            params.securityUrl = this.temp.securityUrl
          } else {
            params.securityUrl = ''
          }
          if (this.temp.xrule) {
            if (!this.temp.xmin) {
              const xresult = this.match(this.temp.xrule, this.temp.xmin, this.temp.xmax)
              params.xpcodex = xresult.codex
              params.xpschema = xresult.schema
            } else {
              this.$message.warning('请输入芯片编码最少位数！')
              return
            }
          }
          if (!this.temp.grule) {
            if (!this.temp.gmin) {
              const gresult = this.match(this.temp.grule, this.temp.gmin, this.temp.gmax)
              params.gpcodex = gresult.codex
              params.gpschema = gresult.schema
            } else {
              this.$message.warning('请输入钢瓶编码最少位数！')
              return
            }
          }
          this.submit(params)
        })
      },
      async submit(params) {
        await saveCorpInfo(params)
        this.$notify({
          title: '提示',
          message: '更新企业配置成功',
          type: 'success',
          duration: 2000
        })
      },
      match(rule, min, max) {
        let reg = ''
        if (rule === 1) {
          reg = '[0-9]'
        } else if (rule === 2) {
          reg = '[a-zA-Z]{1,n}-[0-9]'
        } else if (rule === 3) {
          reg = '[a-zA-Z0-9]'
        }

        if (max) {
          if (parseInt(max) < parseInt(min)) {
            this.$message.warning('最多位不能小于最少位！')
            return
          }
        }

        const codex1 = (parseInt(rule) & 0xF) << 1
        const codex2 = (parseInt(min) & 31) << 5
        const codex3 = (parseInt(max) & 31) << 10
        const codex = codex1 | codex2 | codex3
        if (rule === 2) {
          min = min - 1 + '-n'
          max = max - 1 + '-n'
        }
        const schema = '^' + reg + '{' + min + ',' + max + '}$'

        const result = { codex: codex, schema: schema }
        return result
      }
    }
  }
</script>

<style lang="scss" scoped>
.app-page {
  /deep/ .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
  }
}
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 50%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  line-height: 178px;
  color: #8c939d;
  text-align: center;
}
.avatar {
  display: block;
  width: 178px;
  height: 178px;
}
</style>
